#!/bin/bash

# mediawiki-vagrant installs dont have realpath by default
if ! which realpath > /dev/null; then
	realpath() {
		php -r "echo realpath('$*');"
	}
fi

if hash php7.0 2>/dev/null; then
	export PHP="php7.0"
else
	export PHP="php"
fi

# Note that this isn't loaded in via composer because then composer can
# only be run with php7.0
if [ ! -f "$PHAN" ]; then
	# If no PHAN is specified then try to get location from PATH
	export PHAN="$(which phan)"
	if [ ! -f "$PHAN" ]; then
		echo "The environment variable PHAN must point to the 'phan' file"
		echo "in a checkout of https://github.com/etsy/phan.git"
		echo "Or phan must be included in your PATH"
		exit 1
	fi
else
	export PHAN="$PHP $PHAN"
fi

if [ -z "$MW_INSTALL_PATH" ]; then
	# Figure out where mediawiki is based on the location of this script
	pushd "$(dirname "$0")" > /dev/null
	export MW_INSTALL_PATH="$(git rev-parse --show-toplevel)"
	popd >/dev/null
fi

# If the first argument doesn't start with a -, then it's a path
# to another project (extension, skin, etc.) to analyze
if [[ -n "$1" && "$1" != "-"* ]]; then
	cd $1
	shift
else
	cd "$(dirname "$0")"
fi

# Root directory of project
export ROOT="$(git rev-parse --show-toplevel)"

# Go to the root of this git repo
cd "$ROOT"

export CONFIG_FILE="$ROOT/tests/phan/config.php"
if [ ! -f "$CONFIG_FILE" ]; then
	echo "Could not find a phan config file to apply in"
	echo "$CONFIG_FILE"
	exit 1
fi

# Phan's issues directory
export ISSUES="${ROOT}/tests/phan/issues"
mkdir -p "$ISSUES"

# Get the current hash of HEAD
export REV="$(git rev-parse HEAD)"

# Destination for issues found
export RUN="${ISSUES}/issues-${REV}"


# Run the analysis, emitting output to the
# issues file.
$PHAN \
	--project-root-directory "$ROOT" \
	--config-file "$CONFIG_FILE" \
	--output "php://stdout" \
	"${@}" \
	| php "$MW_INSTALL_PATH/tests/phan/bin/postprocess-phan.php" "${@}" \
	> $RUN

EXIT_CODE="$?"

# Re-link the latest file
rm -f "${ISSUES}/latest"
ln -s "${RUN}" "${ISSUES}/latest"

# Output any issues that were found
cat "${RUN}"

exit $EXIT_CODE
